import { Api, Get, Post } from 'easy-descriptor'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { FetchEventSourceInit } from '@microsoft/fetch-event-source/lib/cjs/fetch'
import { BASE_URL } from '@/utils/http/config'

export type ChatMessage = {
  messageType?: 'user' | 'assistant'
  content: string
  sessionId?: string
  appCode?: string
  maxHistory?: number
  model?: string

  params?: Record<string, any>
}

export type ChatMessageResp = {
  sessionId: string
  messages: {
    type: string
    content: string
  }
}

export type OllamaChatModel = {
  name: string
  model: string
  modified_at: number
  size: number
  digest: string
  details: {
    parent_model: string
    format: string
    family: string
    families: string[]
    parameter_size: string
    quantization_level: string
  }
}
export type OllamaChatModelDetail = OllamaChatModel['details']

@Api()
class AiChatApi {
  @Post('/ai/chat', { timeout: 0 })
  static chat: HttpReq<ChatMessageResp, ChatMessage>

  @Get('/ai/ollama/models')
  static getOllamaModels: HttpReq<OllamaChatModel[]>
}

export const sseChat = (data: ChatMessage, config?: Partial<FetchEventSourceInit>) => {
  return fetchEventSource(`${BASE_URL}/ai/chat`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'text/event-stream'
    },
    body: JSON.stringify(data),
    ...config
    // signal: ctrl.signal,
  })
}
export const chat = AiChatApi.chat
export const getOllamaModels = AiChatApi.getOllamaModels
